package org.lyq.erp.process.users.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.lyq.erp.config.exception.myexception.MyException;
import org.lyq.erp.process.userrank.mapper.TblWxUserrankMapper;
import org.lyq.erp.process.userrank.pojo.TblWxUserrank;
import org.lyq.erp.process.users.mapper.TblWxUsersMapper;
import org.lyq.erp.process.users.pojo.TblWxUsers;
import org.lyq.erp.process.users.pojo.UsersUpdateVo;
import org.lyq.erp.utils.objectcope.ObjectCopeUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TblWxUsersServiceImpl implements TblWxUsersService {

	@Resource
	private TblWxUsersMapper tblWxUsersMapper;
	@Resource
	private TblWxUserrankMapper tblWxUserrankMapper;

	public List<TblWxUsers> selectAllUsers() {
		return this.tblWxUsersMapper.selectAllUsers();
	}

	public List<TblWxUsers> selectByPrimaryKey(String userId) {
		List<TblWxUsers> list = new ArrayList<TblWxUsers>();
		list.add(this.tblWxUsersMapper.selectByPrimaryKey(userId));
		return list;
	}

	@Transactional
	public void updateUsers(UsersUpdateVo usersUpdateVo) throws Exception {
		TblWxUsers users = this.tblWxUsersMapper.selectByPrimaryKey(usersUpdateVo.getUserId());
		if (users != null) {

			if (usersUpdateVo.getRankId() != null) {
				TblWxUserrank userrank = this.tblWxUserrankMapper.selectByPrimaryKey(usersUpdateVo.getRankId());
				BigDecimal userTotalamt = users.getUserTotalamt();
				BigDecimal rankAmtNum = userrank.getRankAmtNum();
				if (userTotalamt == null || rankAmtNum == null) {
					usersUpdateVo.setRankId(null);
				} else if (userTotalamt.compareTo(rankAmtNum) >= 0) {
					usersUpdateVo.setRankId(null);
				} else {
					usersUpdateVo.setUserTotalamt(rankAmtNum);
				}
			}

			TblWxUsers tblWxUsers = new TblWxUsers();
			ObjectCopeUtils.copyProperties(usersUpdateVo, tblWxUsers);
			this.tblWxUsersMapper.updateByPrimaryKeySelective(tblWxUsers);
		} else {
			throw new MyException("系统繁忙");
		}
	}
}
